package com.ilab.service.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.ilab.service.BasicService;

// 添加事务
@Transactional
public abstract class BasicAbstractService implements BasicService {
	
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	// 通过id获取对象
	public Object findById(Class clazz, Serializable id) {

		return this.sessionFactory.getCurrentSession().get(clazz, id);
	}

	// 统一查询方法
	public List executeQuery(String hql, Object[] parameters) {

		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		
		// 注入？值
		if(parameters != null && parameters.length > 0)
		{
			for(int i = 0; i < parameters.length; i++) 
			{
				query.setParameter(i, parameters[i]);
			}
		}
		return query.list();
	}

	// 分页
	public List executeQueryByPage(String hql, Object[] parameters,
			int pageNow, int pageSize) {

		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		
		if(parameters != null && parameters.length > 0)
		{
			for(int i = 0; i < parameters.length; i++) 
			{
				query.setParameter(i, parameters[i]);
			}
		}
		
		// 体现分页
		return query.setFirstResult((pageNow - 1) * pageSize).setMaxResults(pageSize).list();
	}

	// 添加
	public void add(Object obj) {
		this.sessionFactory.getCurrentSession().save(obj);
	}

	// 统一的执行 hql -> 删除， 修改
	public List executeUpdate(String hql, Object[] parameters) {

		return null;
	}

	public Object uniqueQuery(String hql, Object[] parameters) {
		Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
		
		// 给？赋值
		if(parameters != null && parameters.length > 0) {
			for(int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.uniqueResult();
	}

	public int queryPageCount(String hql, Object[] parameters, int pageSize) {
		
		// 获取rowCount
		Object obj = this.uniqueQuery(hql, parameters);
		// obj如果等于rowCount就解决问题了
//		System.out.println(obj);
		int rowCount = Integer.parseInt(obj.toString());
		return (rowCount - 1)/pageSize + 1;
	}

	public void deleteById(Class clazz, Serializable id) {
		Session session = this.sessionFactory.getCurrentSession();
		session.delete(this.findById(clazz, id));
	}

	public void update(Object obj) {
		this.sessionFactory.getCurrentSession().update(obj);
	}
	
	

}
